#include "fpga_interface.h"
#include "target_node.h"
#include <stdint.h>
#include <stdio.h>
#include <string.h>

#define MAX_LINE_LENGTH 100 // 假设CSV文件中每一行不超过100个字符
#define MAX_ENTRIES 65536    // 假设最多读取行数

int main(int argc, char *argv[]) {
    FILE *file;
    char line[MAX_LINE_LENGTH];
    int16_t numbers[MAX_ENTRIES]; // 存储读取的数
    int entry_count = 0;          // 已读取的数的数量
    char finename[50] = "\0";

    strcat(finename, "/mnt/");
    strcat(finename, argv[1]);
    strcat(finename, ".csv");
    printf("%s\n", finename);
    // 打开CSV文件
    file = fopen(finename, "r");
    if (file == NULL) {
        perror("Error opening file");
        return 1;
    }

    // 逐行读取文件
    while (fgets(line, MAX_LINE_LENGTH, file) != NULL && entry_count < MAX_ENTRIES) {
        // 使用fscanf解析行中的数字
        if (sscanf(line, "%hd", &numbers[entry_count]) == 1) {
            entry_count++;
        } else {
            // 如果行不能被解析为数字，可能是格式问题，可以选择忽略或处理错误
            printf("Warning: Could not parse line as number: %d\n", entry_count);
        }
    }

    printf("Total Lines: %d\n", entry_count);

    // 关闭文件
    fclose(file);

    fpga_init(0);

    spi_write_fpga(0, 0x5, 1);

    uint32_t timeout = 32768;
    while (timeout > 0 && spi_read_fpga(0, 0x5)) {
        timeout--;
    }
    
    timeout = 32768;
    while (timeout > 0 && spi_read_fpga(0, 0x6) != 7) {
        timeout--;
    }

    // 清除FIFO
    spi_write_fpga(0, 0x5, 2);
    timeout = 32768;
    while (timeout > 0 && spi_read_fpga(0, 0x5)) {
        timeout--;
    }

    write_play_ddr((uint8_t *)numbers, sizeof(int16_t) * entry_count);
    trigger_da_play(0);

    close_fpga(0);

    return 0;
}
